<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import mqtt from "mqtt";
import ChatBox from "./components/ChatBox.vue";
import SetBox from "./components/SetBox.vue";
import StateBox from "./components/StateBox.vue";
import WebPhone from "./components/WebPhone.vue";
import { getStateInfo } from '@/api/webphone'
import { useChatStore } from '@/stores/chat'

const chatStore = useChatStore()
const showList = ref([]);
const toast = (msg) => {
  showList.value = msg
  setTimeout(() => {
    showList.value = []
  }, 10000);
}
const client = mqtt.connect(import.meta.env.VITE_MQTT_URL, {
  clientId: Math.random().toString().slice(8) - 0,
  username: 'poc',
  password: 'poc@2025',
});

client.on("connect", () => {
  console.log(`连接成功 ${new Date().toLocaleString()}`);
  client.subscribe("poc/agent/#");
});

client.on("message", (topic, message) => {
  let msgObj = message.toString();
  if (JSON.parse(message.toString())) {
    msgObj = JSON.parse(message.toString());
  }
  console.log(`收到消息：${new Date().toLocaleString()}`, topic, msgObj);
});

client.on("error", (error) => {console.error("MQTT连接错误:", error);});
client.on("reconnect", () => {console.log(`正在尝试重新连接... ${new Date().toLocaleString()}`);});
client.on("offline", () => {console.log(`MQTT客户端已离线 ${new Date().toLocaleString()}`);});

const updateZoom = () => {
  document.querySelectorAll('.need-zoom').forEach(el => {
    const zoomVal = window.innerWidth > 1680 ? 1 : window.innerWidth / 1680;
    chatStore.changeZoomVal(zoomVal)
    el.style.zoom = zoomVal;
  });
};

onMounted(async () => {
  updateZoom();
  window.addEventListener('resize', updateZoom);
  
  // 获取空调信息
  const res = await getStateInfo()
  chatStore.changeCarState(res)
});

onUnmounted(() => {
  window.removeEventListener('resize', updateZoom);
});
</script>

<template>
  <div class="home-page">
    <chat-box :client="client" @changeType="chatStore.changeType" @toast="toast"></chat-box>
    <set-box v-show="chatStore.showType === 'battary' || chatStore.showType === 'ac'"></set-box>
    <state-box v-show="showList.length" :showList="showList"></state-box>
    <!-- <web-phone v-show="chatStore.showType === 'phone'"></web-phone> -->
  </div>
</template>
<style>
.home-page {
  background-color: #f5f5f5;
  background-image: url('../assets/images/bgi.png');
  background-size: contain;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  transition: transform 0.3s ease; 
}
</style>
